import { Component, OnInit, Input, Output, EventEmitter, SimpleChanges } from '@angular/core'
import { JsonApiService } from 'app/core/api/json-api.service' //http请求配置引入
import { config } from '../smartadmin.config'
declare var $: any
declare var echarts: any
declare var toMapPoint: any
declare var INFOBOX_AT_TOP
@Component({
  selector: 'sa-chart-bmap',
  templateUrl: './chart-bmap.component.html',
  styleUrls: ['./chart-bmap.css']
})
export class ChartBmapComponent implements OnInit {
  @Input() dataMapAuthority: any //折线图宽度
  @Input() width: any //折线图宽度
  @Input() height: any //折线图高度
  @Input() authority: any //显示AD的权限
  @Input() offDatas: any //是否显示离线警报数据
  @Input() inputParams: any //接收父组件的值 请求后台获取折线图数据 例:{deviceId:'',startTime:'',endTime:''}
  @Input() isBaiduMap: any //是否有地图联动组件交互
  @Input() hideAD: any // checkParams.lookSignal=false
  @Input() hideDB: any // checkParams.loadometer=false
  @Input() hideSP: any // checkParams.carSpeed=false
  @Input() isOpenMap: boolean = false //checkParams.linetoMap=false
  @Input() isAuditData: boolean = true //是否有权限查看审核数据
  @Input() isShowModify: boolean = false //是否默认选中修正数据，在声明周期赋值
  @Input() noAbnormity: any //不显示异常数据
  @Input() myChartId: string = 'chartBmap' //图形标识Id
  @Input() isShowChartTop: boolean = true //是否显示车辆分类,默认不显示
  @Output() private outerSend = new EventEmitter()
  @Output() private outerIsMap = new EventEmitter()
  //折线图配置及画线参数
  myChart: any
  echartOption: any
  yAxiSignal: any
  yAxiWeight: any
  yAxiSpeed: any
  isLoading: boolean = false //判断是否在加载数据中
  checkParams = {
    isAllowCheck: true, // 是否有权限允许查看AD信号等
    lookSignal: true, // ad信号
    loadometer: true, // 地磅数据
    carSpeed: true, // 车辆速度
    linetoMap: false, // 地图联动
    showModify: false, // 数据修正
    checkData: false // 审核数据
  }
  timeShadow: any = [] //没有历史数据区域
  allData = []
  allChartline = [] //所有的折线数据
  passageName = []
  passageArr = []
  loadometerData = []
  carSpeedArr = []
  weightArr = []
  linetoMapData = []
  loadometerArr = []
  //获取异常数据相关参数
  averageTime = 0 //默认判断丢失数据的时间
  lostWeightMark = [] //计算丢失重量的时长
  nullGpsArr = [] //经纬度为空或者0.0的画折线数据
  nullMarkerData = [] //计算经纬度丢失的时长
  isLostGps = false //是否有丢失经纬度
  isHavePoint = 0 //控制判断经纬度丢失起始结束位置计算时间条件
  abnormalMarkLine = null // 异常时间区域
  //父组件传递过来 相关参数
  isInitChart: boolean = true //判断是否初次父组件传递宽高及其他条件渲染图表

  offlineAbParams = []
  clickOffPoint: any = {
    type: '',
    data: {}
  }
  correctParams: any = {
    tracklist: [],
    chart1line: []
  }
  hideOrshowline = []
  legendSleced: any = {}
  private isMoveFlag: boolean = true //防抖节流，控制mousemove触发频率
  alertChartModelInfo: any = {} //echart异常警报信息模板信息
  constructor(private jsonApiService: JsonApiService) { }
  //将数据传递到父组件
  sendParent(data) {
    this.outerSend.emit(data)
  }

  sendisMap() {
    this.outerIsMap.emit(this.checkParams.linetoMap)
  }
  linetoMapChange() {
    this.sendisMap()
  }
  ngOnChanges(changes: SimpleChanges) {
    if (this.inputParams && changes['inputParams']) {
      if (this.inputParams.abnormalMarkLine) {
        this.abnormalMarkLine = this.inputParams.abnormalMarkLine
      }
      this.hideOrshowline = []
      if (!this.inputParams.coefficient) this.inputParams.coefficient = []
      for (let i = 0; i < this.inputParams.coefficient.length; i++) {
        if (!(this.inputParams.coefficient[i] == '0' || this.inputParams.coefficient[i] == 0)) {
          let lineName = '通道' + (i + 1)
          this.hideOrshowline.push(lineName)
        }
      }
      if (this.inputParams.deviceId) {
        let timeCheck = common.correctTimeParams(this.inputParams.startTime, this.inputParams.endTime, 31)
        if (!timeCheck.status) {
          this.jsonApiService.message(timeCheck.message)
          return
        }

        this.askforData()
      }
    }
    if (this.isOpenMap) {
      this.checkParams.linetoMap = true
      this.sendisMap()
    }
  }
  ngOnInit() {
    var that = this
    if (that.authority) {
      that.checkParams.isAllowCheck = false
      that.checkParams.lookSignal = false
      that.checkParams.loadometer = false
    }

    if (that.hideAD) that.checkParams.lookSignal = false
    if (that.hideDB) that.checkParams.loadometer = false
    if (that.hideSP) that.checkParams.carSpeed = false
    if (that.isOpenMap) that.checkParams.linetoMap = true
    that.checkParams.showModify = that.isShowModify

    setTimeout(function () {
      that.initChart()
    }, 300)
  }

  initChart() {
    if (this.isInitChart) {
      this.initChartyAxi()
      this.initChartConfig()
      this.myChart = echarts.init(document.getElementById(this.myChartId))
      if (this.width) {
        // $('.warpBox').width(this.width + "px");
        this.myChart.getDom().style.width = this.width + 'px'
      }
      if (this.height) {
        this.myChart.getDom().style.height = this.height + 'px'
      }
      this.isInitChart = false

      this.myChart.setOption(this.echartOption, true)
      this.myChart.resize()
      $(window).resize(this.myChart.resize)
      this.myChart.on(
        'click',
        function (params) {
          if (params.componentType === 'markPoint') {
            if (params.name == '离线警报' || params.name == '断电警报') {
              this.clickOffPoint = {
                type: 'clickOffPoint',
                data: params.data
              }
              this.sendParent(this.clickOffPoint)
            }
          }
        }.bind(this)
      )
    }
  }

  //重置清空折线图相关参数
  initChartParams() {
    this.allData = [] //echart图后台请求回来的数据
    this.allChartline = [] //所有chart图折线的数组
    this.linetoMapData = [] //地图联动画轨迹数据
    this.loadometerData = [] //后台返回的地磅数据
    this.loadometerArr = [] //拼接成echart数组
    this.weightArr = [] //重量折线的数据
    this.carSpeedArr = [] //速度折线的数据
    this.passageName = [] //ad信号折线名
    this.passageArr = [] //ad信号数据
    this.averageTime = 0 //默认判断丢失数据的时间
    this.lostWeightMark = [] //计算丢失重量的时长
    this.nullGpsArr = [] //经纬度为空或者0.0的画折线数据
    this.nullMarkerData = [] //计算经纬度丢失的时长
    this.isLostGps = false //是否有丢失经纬度
    this.isHavePoint = 0 //控制判断经纬度丢失起始结束位置计算时间条件
    if (this.echartOption) {
      this.echartOption.xAxis.data = []
      this.echartOption.series = []
      this.myChart.setOption(this.echartOption, true)
    }
  }

  getAbnormalData(i) {
    //计算经纬度等于0.0或者丢失的时候是时长start
    if (!this.allData[i] || !this.allData[i].x || this.allData[i].x == '0.0' || this.allData[i].x == '0') {
      if (this.isHavePoint < 1) {
        this.isHavePoint = i
      }
    } else {
      if (this.isHavePoint > 0) {
        var lostTime =
          (common.mmsstoTimestamp(this.allData[i].uploadDate) -
            common.mmsstoTimestamp(this.allData[this.isHavePoint].uploadDate)) /
          1000
        if (lostTime > this.averageTime) {
          var point = {
            value: this.convertTime(lostTime),
            xAxis: this.isHavePoint,
            yAxis: this.allData[this.isHavePoint].weight
          }
          this.nullMarkerData.push(point)
        }
        this.isHavePoint = 0
      }
    } //计算end
    //获取丢失的数据
    if (i < this.allData.length - 1) {
      let lostStartime = common.mmsstoTimestamp(this.allData[i].uploadDate)
      let lostEndtime = common.mmsstoTimestamp(this.allData[i + 1].uploadDate)
      let lostime = (lostEndtime - lostStartime) / 1000
      if (lostime > this.averageTime) {
        var myxy = {
          value: this.convertTime(lostime),
          xAxis: i,
          yAxis: this.allData[i].weight
        }
        this.lostWeightMark.push(myxy)
        //重量时间段丢失
      }
      if (!this.allData[i].x || this.allData[i].x == '0.0' || this.allData[i].x == '0') {
        //经纬度坐标丢失
        if (i > 0) {
          this.isLostGps = true
          this.nullGpsArr[i] = this.allData[i].weight
        }
      }
    }
  }
  /**
   * 获取警报数据,对警报数据分类:离线警报,断电警报;将这两种警报显示在echart折线图上
   */
  getOffDatas(reqdata) {
    this.offlineAbParams = []
    return new Promise(
      function (resolve, reject) {
        let alertArr = []
        if (this.offDatas) {
          this.jsonApiService.http2('alertlog/queryAllTypeDeviceShutDownAlarmList.html', reqdata).subscribe(result => {
            let len = result.data.length
            alertArr = result.data
            let offlineError = []
            if (len > 0) {
              for (let i = 0; i < len; i++) {
                let sort = 0
                result.data[i].flag = 'alert'
                let item = result.data[i]
                let topos = toMapPoint({
                  lng: item.lng,
                  lat: item.lat
                })
                if (topos) {
                  item.lng = topos.lng
                  item.lat = topos.lat
                }
                let tim = common.mmsstoTimestamp(item.offTime)
                for (let _i = sort; _i < this.allData.length; _i++) {
                  let _item = this.allData[_i]
                  let _tim = common.mmsstoTimestamp(_item.uploadDate)
                  if (_tim - tim >= 0 && _i > 0) {
                    sort = _i
                    let errorItem: any = {}
                    if (item.type == 1) {
                      errorItem = {
                        name: '离线警报',
                        value: '离',
                        xAxis: _i - 1,
                        yAxis: this.allData[_i - 1].weight,
                        lostime: '',
                        rangeTime: item.totalSecond ? this.convertTime(item.totalSecond) : '离线中',
                        symbol: 'image://assets/img/trackImage/ofline_jb.png',
                        symbolSize: 24,
                        symbolOffset: ['0', '-50%']
                      }
                    } else if (item.type == 2) {
                      errorItem = {
                        name: '断电警报',
                        value: '',
                        xAxis: _i - 1,
                        yAxis: this.allData[_i - 1].weight,
                        lostime: '',
                        rangeTime: item.totalSecond ? this.convertTime(item.totalSecond) : '断电中',
                        symbol: 'image://assets/img/trackImage/powerOff2.png',
                        symbolSize: 24,
                        symbolOffset: ['0', '-50%']
                      }
                    }
                    for (let keys in item) {
                      errorItem[keys] = item[keys]
                    }
                    offlineError.push(errorItem)
                    break
                  }
                }
              }
            }
            /**
             *   处理警报不在历史数据时间范围之内,但在搜索的时间范围.  将不在历史数据时间范围的数据,补打在历史数据最后时间点上.
             */
            for (let w = 0; w < alertArr.length; w++) {
              let itemAlert = alertArr[w]
              if (
                common.mmsstoTimestamp(itemAlert.offTime) >
                common.mmsstoTimestamp(this.allData[this.allData.length - 1].uploadDate)
              ) {
                let errorItem: any
                let index = alertArr.length - w
                if (itemAlert.type == 1) {
                  errorItem = {
                    name: '离线警报',
                    value: '离',
                    xAxis: this.allData.length - index,
                    yAxis: this.allData[this.allData.length - index].weight,
                    lostime: '',
                    rangeTime: itemAlert.totalSecond ? this.convertTime(itemAlert.totalSecond) : '离线中',
                    symbol: 'image://assets/img/trackImage/ofline_jb.png',
                    symbolSize: 24,
                    symbolOffset: ['0', '-50%']
                  }
                } else if (itemAlert.type == 2) {
                  errorItem = {
                    name: '断电警报',
                    value: '',
                    xAxis: this.allData.length - index,
                    yAxis: this.allData[this.allData.length - index].weight,
                    lostime: '',
                    rangeTime: itemAlert.totalSecond ? this.convertTime(itemAlert.totalSecond) : '断电中',
                    symbol: 'image://assets/img/trackImage/powerOff2.png',
                    symbolSize: 24,
                    symbolOffset: ['0', '-50%']
                  }
                }
                if (errorItem) {
                  for (let keys in itemAlert) {
                    errorItem[keys] = itemAlert[keys]
                  }
                  offlineError.push(errorItem)
                }
              }
            }
            this.offlineAbParams = offlineError
            resolve()
          })
        } else {
          resolve()
        }
      }.bind(this)
    )
  }
  //后台获取数据
  askforData() {
    if (!this.inputParams.deviceId) {
      this.jsonApiService.message('设备编号不能为空')
      return
    }
    this.loadometerData = []
    this.loadometerArr = []
    let reqdata
    // 没有权限默认提交修正后数据
    if (this.dataMapAuthority == 'notAllow') {
      reqdata =
        'deviceId=' +
        this.inputParams.deviceId +
        '&startTime=' +
        this.inputParams.startTime +
        '&endTime=' +
        this.inputParams.endTime +
        '&showModify=true'
    } else {
      reqdata =
        'deviceId=' +
        this.inputParams.deviceId +
        '&startTime=' +
        this.inputParams.startTime +
        '&endTime=' +
        this.inputParams.endTime +
        '&showModify=' +
        this.checkParams.showModify
    }
    this.jsonApiService.http2('weighbridge/weightforreal.html', reqdata).subscribe(result => {
      if (result.data.length >= 1) {
        this.loadometerData = result.data
      }
    })
    this.initChartParams()

    layer.load()
    let postUrl = 'stats/draw.html'
    // 审核默认提交修正后数据
    if (this.checkParams.checkData) {
      postUrl = 'stats/drawforfixdatacheck.html'
      reqdata =
        'deviceId=' +
        this.inputParams.deviceId +
        '&startTime=' +
        this.inputParams.startTime +
        '&endTime=' +
        this.inputParams.endTime +
        '&showModify=true'
    }
    this.jsonApiService.http2(postUrl, reqdata).subscribe(data => {
      layer.closeAll('loading')
      if (data.data.length < 2) {
        this.isLoading = false
        this.jsonApiService.message('没有数据')
        this.sendParent({ type: 'trackline', data: [] })
        return
      }
      this.allData = data.data

      /**
       * 对筛选时间范围内,返回的历史数据做处理,对于数据缺失的时间段进行数据的补点,在echart对应显示灰色区域,表明该时间段范围内没有历史数据.
       */
      this.timeShadow = []
      if (
        common.mmsstoTimestamp(this.allData[0].uploadDate) - common.mmsstoTimestamp(this.inputParams.startTime) >
        150 * 1000
      ) {
        // 判断曲线数据前有没有过磅数据,有过磅数据,显示无数据区域,没有过磅数据则不显示无数据区域
        let hasWeightInEmptyDataStartTime: boolean = false
        for (let i = 0; i < this.loadometerData.length; i++) {
          let item = this.loadometerData[i]
          if (
            common.mmsstoTimestamp(this.inputParams.startTime) < common.mmsstoTimestamp(item.date) &&
            common.mmsstoTimestamp(item.date) < common.mmsstoTimestamp(this.allData[0].uploadDate)
          ) {
            hasWeightInEmptyDataStartTime = true
            break
          }
        }
        if (hasWeightInEmptyDataStartTime) {
          let emptyDataStartTime = [] //存放搜索开始时间空数据补点的集合
          for (
            let t = common.mmsstoTimestamp(this.inputParams.startTime);
            t < common.mmsstoTimestamp(this.allData[0].uploadDate);
            t = t + 150 * 1000
          ) {
            let temDate = common.getTimeMmss(new Date(t))
            let temObj = {
              aCH1: '',
              aCH2: '',
              aCH3: '',
              aCH4: '',
              aCH5: '',
              aCH6: '',
              aCH7: '',
              aCH8: '',
              aCH9: '',
              aCH10: '',
              aCH11: '',
              aCH12: '',
              aCH13: '',
              aCH14: '',
              aCH15: '',
              aCH16: '',
              checkGps: '',
              checkWeight: '',
              deviceId: this.inputParams.deviceId,
              handBrakeHardwareStatus: '',
              handBrakeSoftwareStatus: '',
              mWeight: '',
              rectifyWeight: '',
              rectifyX: '',
              rectifyY: '',
              speed: '',
              uploadDate: temDate,
              weight: '',
              x: this.allData[0].x,
              y: this.allData[0].y
            }
            emptyDataStartTime.push(temObj)
          }

          let emptyShadowStart = [
            {
              name: '无数据',
              itemStyle: {
                color: '#ddd',
                opacity: 0.3
              },
              label: {
                color: '#333',
                fontSize: '16',
                position: ['50%', '50%'],
                offset: [-24, -8]
              },
              emphasis: {
                itemStyle: {
                  color: '#ddd',
                  opacity: 0.5
                },
                label: {
                  position: ['50%', '50%'],
                  offset: [-24, -8]
                }
              },
              xAxis: this.inputParams.startTime
            },
            {
              xAxis: this.allData[0].uploadDate
            }
          ]
          this.timeShadow.push(emptyShadowStart)
          this.allData = emptyDataStartTime.concat(this.allData)
        }
      }
      if (
        common.mmsstoTimestamp(this.inputParams.endTime) -
        common.mmsstoTimestamp(this.allData[this.allData.length - 1].uploadDate) >
        150 * 1000
      ) {
        // 判断曲线数据后有没有过磅数据,有过磅数据,显示无数据区域,没有过磅数据则不显示无数据区域
        let hasWeightInEmptyDataEndTime: boolean = false
        for (let i = 0; i < this.loadometerData.length; i++) {
          let item = this.loadometerData[i]
          if (
            common.mmsstoTimestamp(this.allData[this.allData.length - 1].uploadDate) <
            common.mmsstoTimestamp(item.date) &&
            common.mmsstoTimestamp(item.date) < common.mmsstoTimestamp(this.inputParams.endTime)
          ) {
            hasWeightInEmptyDataEndTime = true
            break
          }
        }
        if (hasWeightInEmptyDataEndTime) {
          let emptyDataEndTime = [] //存放搜索结束时间空数据补点的集合
          let EndTime: string
          if (new Date().getTime() - common.mmsstoTimestamp(this.inputParams.endTime) > 0) {
            EndTime = this.inputParams.endTime
          } else {
            EndTime = common.getNowTime()
          }
          for (
            let t = common.mmsstoTimestamp(this.allData[this.allData.length - 1].uploadDate) + 150 * 1000;
            t < common.mmsstoTimestamp(EndTime);
            t = t + 150 * 1000
          ) {
            let temDate = common.getTimeMmss(new Date(t))
            let temObj = {
              aCH1: '',
              aCH2: '',
              aCH3: '',
              aCH4: '',
              aCH5: '',
              aCH6: '',
              aCH7: '',
              aCH8: '',
              aCH9: '',
              aCH10: '',
              aCH11: '',
              aCH12: '',
              aCH13: '',
              aCH14: '',
              aCH15: '',
              aCH16: '',
              checkGps: '',
              checkWeight: '',
              deviceId: this.inputParams.deviceId,
              handBrakeHardwareStatus: '',
              handBrakeSoftwareStatus: '',
              mWeight: '',
              rectifyWeight: '',
              rectifyX: '',
              rectifyY: '',
              speed: '',
              uploadDate: temDate,
              weight: '',
              x: this.allData[this.allData.length - 1].x,
              y: this.allData[this.allData.length - 1].y
            }
            emptyDataEndTime.push(temObj)
          }
          let emptyShadowEnd = [
            {
              name: '无数据',
              itemStyle: {
                color: '#ddd',
                opacity: 0.5
              },
              label: {
                color: '#333',
                fontSize: '16',
                position: ['50%', '50%'],
                offset: [-24, -8]
              },
              emphasis: {
                itemStyle: {
                  color: '#ddd',
                  opacity: 0.5
                },
                label: {
                  position: ['50%', '50%'],
                  offset: [-24, -8]
                }
              },
              xAxis: this.allData[this.allData.length - 1].uploadDate
            },
            {
              xAxis: emptyDataEndTime[emptyDataEndTime.length - 1].uploadDate
            }
          ]
          this.timeShadow.push(emptyShadowEnd)
          this.allData = this.allData.concat(emptyDataEndTime)
        }
      }
      this.getOffDatas(reqdata).then(() => {
        if (this.checkParams.checkData) {
          this.coupudCheckDatas()
        } else {
          this.coupudChartDatas()
        }
      })
    })
  }
  //计算折线图的数据
  coupudChartDatas() {
    this.carSpeedArr = []
    let timeValue = []
    let len = this.allData.length
    this.averageTime = this.getAverageTime() //计算数据丢失的过滤时间阈值
    const points = []
    for (var i = 0; i < len; i++) {
      timeValue[i] = this.allData[i].uploadDate //x时间轴数据
      this.weightArr[i] = parseFloat(this.allData[i].weight) //重量
      if (this.weightArr[i] < 0 && this.weightArr[i] >= -1) {
        this.weightArr[i] = 0
      }
      let _speed = parseFloat(this.allData[i].speed) //速度
      if (_speed > -1) {
        this.carSpeedArr[i] = parseFloat(this.allData[i].speed)
      } else {
        this.carSpeedArr[i] = 0
      }
      this.loadometerArr[i] = '-' //地磅数据
      this.nullGpsArr[i] = '-' //经纬度空
      if (!this.noAbnormity) this.getAbnormalData(i)
      // var mapPoint = toMapPoint(this.allData[i])
      // let lngX = +mapPoint.lng
      // let latY = +mapPoint.lat
      // if (lngX > 0 || lngX < 0) {
      //   if (latY > 0 || latY < 0) {
      //     this.linetoMapData[i] = this.allData[i]
      //   }
      // }
      const mapPoint = toMapPoint(this.allData[i])
      if(mapPoint) {
        points.push(mapPoint)
      }
    }
    this.linetoMapData = [...points]
    this.sendParent({ type: 'trackline', data: this.linetoMapData })

    for (let i = 0; i < this.offlineAbParams.length; i++) {
      let item = this.offlineAbParams[i]
      let isFind = false
      for (let _i = 0; _i < this.lostWeightMark.length; _i++) {
        let iem = this.lostWeightMark[_i]
        if (iem.flag) {
          if (item.xAxis == iem.xAxis) {
            item.xAxis = item.xAxis + 1
            item.lostime = iem.lostime
            this.lostWeightMark.push(item)
            isFind = true
            break
          }
        } else {
          if ((item.xAxis < iem.xAxis + 1 && item.xAxis > iem.xAxis - 1) || item.xAxis == iem.xAxis) {
            item.lostime = iem.lostime
            this.lostWeightMark[_i] = item
            isFind = true
            break
          }
        }
      }
      if (!isFind) this.lostWeightMark.push(item)
    }
    //		for (let i=0;i<this.offlineAbParams.length;i++){
    //			let item =this.offlineAbParams[i];
    //			let isFind=false;
    //			for(let _i=0;_i<this.lostWeightMark.length;_i++){
    //				let iem=this.lostWeightMark[_i];
    //				if(item.xAxis < iem.xAxis+2 && item.xAxis > iem.xAxis-2){
    //					item.lostime=iem.lostime;
    //					this.lostWeightMark[_i]=item;
    //					isFind=true;
    //					break;
    //				}
    //			}
    //			if(!isFind) this.lostWeightMark.push(item);
    //		}

    //警戒线
    if (!this.inputParams.timeShadowList) this.inputParams.timeShadowList = []
    var timeShadowList = this.inputParams.timeShadowList
    if (!this.inputParams.cordonLineMarkArea) this.inputParams.cordonLineMarkArea = []
    var cordonLineMarkArea = this.inputParams.cordonLineMarkArea
    //首先在横坐标找出某个点
    for (var j = 0; j < timeShadowList.length; j++) {
      for (var k = 0; k < this.allData.length; k++) {
        if (
          this.allData[k].uploadDate.substring(0, this.allData[k].uploadDate.length - 3) ==
          timeShadowList[j].xAxis.substring(0, timeShadowList[j].xAxis.length - 3)
        ) {
          if (this.allData[k].uploadDate != timeShadowList[j].xAxis) {
            timeShadowList[j].xAxis = this.allData[k].uploadDate
          }
        }
      }
    }

    //首先在横坐标找出某个点
    for (var a = 0; a < cordonLineMarkArea.length; a++) {
      for (var b = 0; b < this.allData.length; b++) {
        if (
          this.allData[b].uploadDate.substring(0, this.allData[b].uploadDate.length - 3) ==
          cordonLineMarkArea[a][0].xAxis.substring(0, cordonLineMarkArea[a][0].xAxis.length - 3)
        ) {
          if (this.allData[b].uploadDate != cordonLineMarkArea[a][0].xAxis) {
            cordonLineMarkArea[a][0].xAxis = this.allData[b].uploadDate
          }
        }
        if (
          this.allData[b].uploadDate.substring(0, this.allData[b].uploadDate.length - 3) ==
          cordonLineMarkArea[a][1].xAxis.substring(0, cordonLineMarkArea[a][1].xAxis.length - 3)
        ) {
          if (this.allData[b].uploadDate != cordonLineMarkArea[a][1].xAxis) {
            cordonLineMarkArea[a][1].xAxis = this.allData[b].uploadDate
          }
        }
      }
    }

    this.allChartline = []
    if (this.abnormalMarkLine) {
      let abnormalMarkLine = null
      abnormalMarkLine = this.abnormalMarkLine
      this.initAbnormalMarkLine(abnormalMarkLine, this.allData)
    }

    var weightLine = {
      name: '重量（吨）',
      type: 'line',
      borderWidth: 5,
      data: this.weightArr,
      itemStyle: {
        color: '#c23531'
      },
      markArea: {
        data: cordonLineMarkArea
      },
      markPoint: {
        data: this.lostWeightMark
      },
      markLine: {
        lineStyle: {
          color: '#ff00ff',
          opacity: 0.5,
          width: 2
        },
        silent: true,
        //yAxisIndex: 0,
        symbol: 'none', //去掉箭头
        data: timeShadowList
      }
    }
    this.allChartline.push(weightLine)
    //时间轴
    this.echartOption.xAxis.data = timeValue
    //ad信号
    this.showAdSignal()
    if (this.checkParams.carSpeed) {
      this.yAxiSpeed.min = 0
      this.yAxiSpeed.max = 120
      this.showCarSpeed()
    }
    if (this.checkParams.loadometer) {
      this.showLoadometer()
    }
    if (this.isLostGps) {
      this.allChartline.push({
        name: 'GPS异常',
        type: 'line',
        itemStyle: {
          color: 'gray'
        },
        lineStyle: {
          width: 3 //折线宽度
        },
        data: this.nullGpsArr,
        markPoint: {
          data: this.nullMarkerData
        }
      })
    }
    this.legendSleced['手刹信号'] = false
    this.echartOption.legend.selected = this.legendSleced
    this.yAxiSignal.show = this.checkParams.lookSignal
    this.yAxiSpeed.show = this.checkParams.carSpeed
    this.echartOption.yAxis = [this.yAxiWeight, this.yAxiSignal, this.yAxiSpeed]
    this.echartOption.series = this.allChartline

    this.jsonApiService
      .http2('realtime/getRealTimeDataForBase.html', 'deviceId=' + this.inputParams.deviceId)
      .subscribe(result => {
        if (result.data.unit == '2') {
          this.echartOption.series[0].name = '重量（千克）'
        }
        this.myChart.setOption(this.echartOption, true)
        $(window).trigger('resize')
        this.isLoading = false
        this.initChartEvent() //初始化echart事件
      })
  }

  initAbnormalMarkLine(_abnormalMarkLine: any, list: any[]) {
    const abnormalMarkLine = JSON.parse(JSON.stringify(_abnormalMarkLine))
    if (list.length < 1) {
      return
    }
    const start = Date.parse(new Date(abnormalMarkLine.markArea.data[0][0].xAxis) as any)
    const end = Date.parse(new Date(abnormalMarkLine.markArea.data[0][1].xAxis) as any)
    const firstPoint = Date.parse(new Date(list[0].uploadDate) as any)
    const lastPoint = Date.parse(new Date(list[list.length - 1].uploadDate) as any)
    if (start > lastPoint || end < firstPoint) {
      return
    }
    const dataFirst = { xAxis: '' }
    const dataSec = { xAxis: '' }
    for (let i = 0; i < list.length; i++) {
      const currentTimePoint = list[i].uploadDate ? Date.parse(new Date(list[i].uploadDate) as any) : 0
      if (!dataFirst.xAxis) {
        if (currentTimePoint >= start) {
          dataFirst.xAxis = list[i].uploadDate
        }
      }
      if (!dataSec.xAxis) {
        if (lastPoint <= end) {
          dataSec.xAxis = list[list.length - 1].uploadDate
        }
        if (currentTimePoint > end) {
          dataSec.xAxis = list[i].uploadDate
        }
      }
    }
    abnormalMarkLine.markArea.data[0] = [dataFirst, dataSec]
    this.allChartline.push(abnormalMarkLine)
  }
  /**
   *  echart事件初始化
   */
  initChartEvent() {
    let that = this
    let alertPromptBox = $('.alertPromptBox')
    this.myChart.on('mousemove', function (params, event) {
      if (that.isMoveFlag) {
        that.isMoveFlag = false
        if (params.componentType === 'markPoint') {
          if (params.name == '离线警报' || params.name == '断电警报') {
            params.data.onTime = params.data.onTime ? params.data.onTime : '无'
            that.alertChartModelInfo = params.data
            var e = event || window.event
            var x = e.offsetX - 272
            var y = e.offsetY - 32 > 260 ? e.offsetY - 32 : e.offsetY - 120
            alertPromptBox.show().animate({ left: x + 'px', top: y + 'px' }, 10)
          }
        }
        //				that.myMap.closeInfoWindow(); //关闭信息窗口
        setTimeout(() => {
          that.isMoveFlag = true
        }, 80)
      }
    })
    this.myChart.on('mouseout', function (params) {
      alertPromptBox.hide()
    })
  }
  //获取修正后的轨迹跟折线数据
  getCorrectDatas(result) {
    return new Promise(
      function (resolve, reject) {
        if (result.length < 2) {
          return
        }
        this.correctParams = {
          tracklist: [],
          chart1line: []
        }
        if (this.checkParams.showModify) {
          for (let i = 0; i < result.length; i++) {
            this.correctParams.chart1line[i] = result[i].rectifyWeight
            this.correctParams.tracklist.push(result[i])
          }
        }
        resolve()
      }.bind(this)
    )
  }
  //计算选择审核数据时候的数据
  coupudCheckDatas() {
    this.carSpeedArr = []
    let timeValue = []
    let len = this.allData.length
    this.averageTime = this.getAverageTime()
    this.correctParams = {
      tracklist: [],
      chart1line: []
    }
    for (var i = 0; i < len; i++) {
      timeValue[i] = this.allData[i].uploadDate //x时间轴数据
      this.weightArr[i] = parseFloat(this.allData[i].weight) //重量
      if (this.weightArr[i] < 0 && this.weightArr[i] >= -1) {
        this.weightArr[i] = 0
      }
      let _speed = parseFloat(this.allData[i].speed) //速度
      if (_speed > -1) {
        this.carSpeedArr[i] = parseFloat(this.allData[i].speed)
      } else {
        this.carSpeedArr[i] = 0
      }
      this.loadometerArr[i] = '-' //地磅数据
      this.nullGpsArr[i] = '-' //经纬度空

      if (!this.noAbnormity) this.getAbnormalData(i)
      // var mapPoint = toMapPoint(this.allData[i])
      // let lngX = +mapPoint.lng
      // let latY = +mapPoint.lat
      // if (lngX > 0 || lngX < 0) {
      //   if (latY > 0 || latY < 0) {
      //     this.linetoMapData.push(this.allData[i])
      //   }
      // }
      const mapPoint = toMapPoint(this.allData[i])
      if(mapPoint) {
        this.linetoMapData.push(mapPoint)
      }
      this.correctParams.chart1line.push(this.allData[i].rectifyWeight)
      this.correctParams.tracklist.push(this.allData[i])
    }
    for (let i = 0; i < this.offlineAbParams.length; i++) {
      let item = this.offlineAbParams[i]
      let isFind = false
      for (let _i = 0; _i < this.lostWeightMark.length; _i++) {
        let iem = this.lostWeightMark[_i]
        if (item.xAxis < iem.xAxis + 2 && item.xAxis > iem.xAxis - 2) {
          item.lostime = iem.lostime
          this.lostWeightMark[_i] = item
          isFind = true
          break
        }
      }
      if (!isFind) this.lostWeightMark.push(item)
    }
    this.allChartline = []

    this.sendParent({
      type: 'trackline',
      data: {
        track1: this.linetoMapData,
        correct: this.correctParams.tracklist
      }
    })
    if (this.correctParams.chart1line.length > 3) {
      var correctWeight = {
        name: '修正后重量',
        type: 'line',
        borderWidth: 5,
        data: this.correctParams.chart1line,
        itemStyle: {
          color: '#c23531'
        }
      }
      this.allChartline.push(correctWeight)
    }
    var weightLine = {
      name: '原始重量',
      type: 'line',
      borderWidth: 5,
      data: this.weightArr,
      itemStyle: {
        color: '#4169e1'
      },
      markPoint: {
        data: this.lostWeightMark
      }
    }
    this.allChartline.push(weightLine)
    //时间轴
    this.echartOption.xAxis.data = timeValue
    //ad信号
    this.showAdSignal()
    if (this.checkParams.carSpeed) {
      this.yAxiSpeed.min = 0
      this.yAxiSpeed.max = 120
      this.showCarSpeed()
    }
    if (this.checkParams.loadometer) {
      this.showLoadometer()
    }
    if (this.isLostGps) {
      this.allChartline.push({
        name: 'GPS异常',
        type: 'line',
        itemStyle: {
          color: 'gray'
        },
        lineStyle: {
          width: 3 //折线宽度
        },
        data: this.nullGpsArr,
        markPoint: {
          data: this.nullMarkerData
        }
      })
    }
    this.legendSleced['手刹信号'] = false
    this.echartOption.legend.selected = this.legendSleced
    this.yAxiSignal.show = this.checkParams.lookSignal
    this.yAxiSpeed.show = this.checkParams.carSpeed
    this.echartOption.yAxis = [this.yAxiWeight, this.yAxiSignal, this.yAxiSpeed]
    this.echartOption.series = this.allChartline
    this.myChart.setOption(this.echartOption, true)
    this.isLoading = false
    this.myChart.resize()
  }
  //绘画ad信号折线,及丢失数据点.
  showAdSignal() {
    this.passageName = []
    this.passageArr = []
    var data = this.allData
    var len = data.length
    let wareStatusArr = [] //手刹信号
    //nullPassArr中对应的值为空的时候,从allPassArr移除对应的通道数据,最终得到filterArr过滤后的数据this.passageArr
    var allPassArr = [] //16通道所有的数组
    var nullPassArr = [] //记录通道全部数据是否为空.,默认值为true
    for (var z = 0; z < 16; z++) {
      var newArr = new Array()
      allPassArr.push(newArr)
      nullPassArr.push(true)
    }
    for (var i = 0; i < len; i++) {
      var handSingal = parseFloat(data[i].handBrakeHardwareStatus) * 10 //手刹信号放大10万倍
      if (handSingal >= 0 || handSingal < 0) {
        wareStatusArr[i] = handSingal
      }
      for (var j = 0; j < 16; j++) {
        var name = 'aCH' + (j + 1)
        var passVal = parseFloat(data[i][name]) //获取16个通道的值;
        allPassArr[j][i] = passVal
        if (passVal > 0 || passVal < 0) {
          nullPassArr[j] = false
        }
      }
    }
    this.legendSleced = {}
    for (var _z = 0; _z < nullPassArr.length; _z++) {
      if (!nullPassArr[_z]) {
        var passName = '通道' + (_z + 1)
        this.passageName.push(passName)
        this.passageArr.push(allPassArr[_z])
        if (this.hideOrshowline.indexOf(passName) < 0) {
          this.legendSleced[passName] = false
        }
      }
    }
    this.passageName.push('手刹信号')
    this.passageArr.push(wareStatusArr)
    if (this.checkParams.lookSignal) {
      for (var _i = 0; _i < this.passageName.length; _i++) {
        var obj = {
          name: this.passageName[_i],
          type: 'line',
          yAxisIndex: 1,
          itemStyle: {
            color: common.lineGetColor(_i)
          },
          lineStyle: {
            width: 2, //折线宽度
            opacity: 0.75
          },
          data: this.passageArr[_i]
        }
        if (this.passageName[_i] === '手刹信号') {
          obj.itemStyle = {
            color: '#8B668B'
          }
          obj.yAxisIndex = 0
        }
        this.allChartline.push(obj)
      }
    }
  }
  //地磅数据赋值到对应的折线数据位置上,若数据上有值则往后移
  loadometerVoluation(sort, weight) {
    if (sort + 1 <= this.loadometerArr.length) {
      if (this.loadometerArr[sort + 1] == '-') {
        this.loadometerArr[sort + 1] = weight
      } else {
        this.loadometerVoluation(sort + 1, weight)
      }
    }
  }
  //获取地磅数据在chart图表显示.
  showLoadometer() {
    var orderIndex = 0
    for (var x = 0; x < this.loadometerData.length; x++) {
      var time1 = common.mmsstoTimestamp(this.loadometerData[x].date)
      for (var i = orderIndex; i < this.allData.length; i++) {
        var time2 = common.mmsstoTimestamp(this.allData[i].uploadDate)
        orderIndex++
        if (time2 - time1 >= 0) {
          let lmWeight = parseFloat(this.loadometerData[x].weight)
          this.loadometerVoluation(i - 1, lmWeight)
          break
        }
      }
    }
    if (this.loadometerData.length >= 1) {
      let obj = {
        name: '地磅数据',
        type: 'scatter',
        yAxisIndex: 0,
        itemStyle: {
          color: 'orange'
        },
        data: this.loadometerArr
      }
      this.allChartline.push(obj)
    }
  }
  //绘画车辆速度折线
  showCarSpeed() {
    let obj = {
      name: '车辆速度',
      type: 'line',
      yAxisIndex: 2,
      itemStyle: {
        normal: {
          color: '#5793f3',
          lineStyle: {
            width: 1, //折线宽度
            opacity: 0.5
          }
        }
      },
      data: this.carSpeedArr,
      areaStyle: {
        color: 'rgba(83, 146, 230,0.5)'
      }
    }
    this.allChartline.push(obj)
  }
  //ad信号选中画信号折线
  signalChange() {
    let len = this.passageArr.length
    if (len >= 1) {
      if (this.checkParams.lookSignal) {
        for (var i = 0; i < len; i++) {
          //添加传感器通道数据
          var obj = {
            name: this.passageName[i],
            type: 'line',
            yAxisIndex: 1,
            itemStyle: {
              color: common.lineGetColor(i)
            },
            lineStyle: {
              width: 2, //折线宽度
              opacity: 0.75
            },
            data: this.passageArr[i]
          }
          if (this.passageName[i] === '手刹信号') {
            obj.itemStyle = {
              color: '#8B668B'
            }
            obj.yAxisIndex = 0
          }
          this.allChartline.push(obj)
        }
      } else {
        var _len = this.allChartline.length
        for (var _i = 0; _i < _len; _i++) {
          let findIndex = this.passageName.indexOf(this.allChartline[_i].name)
          if (findIndex > -1) {
            this.allChartline.splice(_i, 1)
            _len = _len - 1
            _i = _i - 1
          }
        }
      }
      this.yAxiSignal.show = this.checkParams.lookSignal
      this.yAxiSpeed.show = this.checkParams.carSpeed
      this.echartOption.yAxis = [this.yAxiWeight, this.yAxiSignal, this.yAxiSpeed]
      this.echartOption.series = this.allChartline
      this.myChart.setOption(this.echartOption, true)
    }
  }
  //地磅数据选中画折线
  loadometerChange() {
    if (this.allData.length < 2) {
      return
    }
    if (this.loadometerData.length >= 1) {
      if (this.checkParams.loadometer) {
        this.showLoadometer()
      } else {
        let len = this.allChartline.length
        for (var i = 0; i < len; i++) {
          if (this.allChartline[i].name === '地磅数据') {
            this.allChartline.splice(i, 1)
            break
          }
        }
      }
      this.echartOption.series = this.allChartline
      this.myChart.setOption(this.echartOption, true)
    } else {
      if (this.checkParams.loadometer) {
        this.jsonApiService.message('该时间段没有地磅数据')
      }
    }
  }
  //车辆速度选中画折线
  carSpeedChange() {
    if (this.carSpeedArr.length >= 1) {
      if (this.checkParams.carSpeed) {
        this.yAxiSpeed.min = 0
        this.yAxiSpeed.max = 120
        this.showCarSpeed()
      } else {
        this.yAxiSpeed.min = undefined
        this.yAxiSpeed.max = undefined
        let len = this.allChartline.length
        for (var i = 0; i < len; i++) {
          if (this.allChartline[i].name === '车辆速度') {
            this.allChartline.splice(i, 1)
            break
          }
        }
      }
      this.yAxiSignal.show = this.checkParams.lookSignal
      this.yAxiSpeed.show = this.checkParams.carSpeed
      this.echartOption.yAxis = [this.yAxiWeight, this.yAxiSignal, this.yAxiSpeed]
      this.echartOption.series = this.allChartline

      this.myChart.setOption(this.echartOption, true)
    }
  }
  //修正数据选中变更
  modifyChange() {
    if (this.isLoading) {
      this.jsonApiService.message('数据正在加载中,请稍后....')
      return
    }
    if (this.allData.length < 1) {
      return
    }
    this.isLoading = true
    this.askforData()
  }
  //计算数据丢失的阈值
  getAverageTime() {
    /**
     * 计算采样周期,用于判断重量丢失的阈值
     * 取10组历史数据,取中位数作为数据采样的频率
     */
    let temFilterArr: any = []
    let filterTimeDefault = 0
    if (this.allData.length > 10) {
      for (let i = 0; i < 11; i++) {
        let time1 = common.mmsstoTimestamp(this.allData[i].uploadDate)
        let time2 = common.mmsstoTimestamp(this.allData[i + 1].uploadDate)
        let diffTime = (time2 - time1) / 1000
        temFilterArr.push(diffTime)
      }
      temFilterArr.sort(function (a, b) {
        return a - b
      })
      filterTimeDefault = Number(temFilterArr[6]) * 1.5 //取中位数作为计算数据丢失的阈值
    } else {
      filterTimeDefault =
        ((common.mmsstoTimestamp(this.allData[1].uploadDate) - common.mmsstoTimestamp(this.allData[0].uploadDate)) /
          1000) *
        1.5
    }
    filterTimeDefault = filterTimeDefault > 150 ? filterTimeDefault : 150

    //		let result=5*60;
    //		let max=this.allData.length;
    //		//	if(max>10) max=10;
    //		for(var i = 0; i <max-3; i++) {
    //			let time1=common.mmsstoTimestamp(this.allData[i].uploadDate)/1000;
    //			let time2=common.mmsstoTimestamp(this.allData[i+1].uploadDate)/1000;
    //			let time3=common.mmsstoTimestamp(this.allData[i+2].uploadDate)/1000;
    //			let timeCha=time2-time1;
    //			if(time3-time2==timeCha){
    //				if(timeCha>result) result=timeCha*1.5;
    //				break;
    //			}
    //		}
    return filterTimeDefault
  }
  //转换时间格式
  convertTime(timeInt) {
    var d, h, m, s
    if (timeInt >= 0) {
      d = Math.floor(timeInt / 60 / 60 / 24)
      h = Math.floor((timeInt / 60 / 60) % 24)
      m = Math.floor((timeInt / 60) % 60)
      s = Math.floor(timeInt % 60)
    }
    if (d < 1) {
      if (h < 1) {
        // 	 return m+'分'+s+'秒';
        return '约' + m + '分'
      } else {
        return h + '小时' + m + '分'
      }
    } else {
      return d + '天' + h + '小时' + m + '分'
    }
  }
  ngOnDestroy() { }
  initChartConfig() {
    this.echartOption = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross' //十字星
        },
        formatter: function (params) {
          if (this.checkParams.linetoMap) {
            var paramIndex = params[0].dataIndex
            var pointObj = this.linetoMapData[paramIndex]
            if (!pointObj || pointObj.x == '' || pointObj.x == '0') {
              return
            }
            this.sendParent({ type: 'movePoint', data: pointObj })
            if (!window.event) return
            if (!window.event.type) return
            var triggerType = window.event.type //触发类型
            if (triggerType == 'click') {
              if (this.clickOffPoint.type == 'clickOffPoint') {
                this.sendParent(this.clickOffPoint)
                this.clickOffPoint = {}
              } else {
                this.sendParent({ type: 'clickPoint', data: pointObj })
              }
            }
          }
          var res = ''
          var len = params.length
          for (var i = 0; i < len; i++) {
            res = res + params[i].marker + params[i].seriesName + ':' + params[i].data + '</br>'
          }
          return res
        }.bind(this)
      },
      grid: {
        left: '48',
        right: '120',
        top: '68',
        bottom: '18%'
      },
      toolbox: {
        feature: {
          dataView: { show: false, readOnly: false },
          restore: { show: false },
          saveAsImage: { show: false }
        }
      },
      legend: {
        selected: {}
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: []
      },
      yAxis: [this.yAxiWeight],

      dataZoom: [
        {
          realtime: true
        },
        {
          type: 'inside',
          realtime: true
        }
      ],
      series: [
        {
          name: '重量',
          type: 'line',
          data: []
        }
      ]
    }
  }
  initChartyAxi() {
    this.yAxiWeight = {
      show: true,
      name: '重量',
      type: 'value',
      position: 'left',
      min: undefined,
      max: undefined,
      offset: undefined,
      axisLine: {
        lineStyle: {
          color: 'gray'
        }
      },
      axisLabel: {
        formatter: '{value}'
      }
    }
    this.yAxiSignal = {
      show: false,
      name: '信号',
      splitLine: {
        show: false
      },
      type: 'value',
      position: 'right',
      min: undefined,
      max: undefined,
      offset: undefined,
      axisLine: {
        lineStyle: {
          color: '#5c427c'
        }
      },
      axisLabel: {
        formatter: '{value}'
      }
    }
    this.yAxiSpeed = {
      show: false,
      name: '速度 KM/H',
      splitLine: {
        show: false
      },
      type: 'value',
      min: undefined,
      max: undefined,
      offset: 60,
      position: 'right',
      axisLine: {
        lineStyle: {
          color: '#5793f3'
        }
      },
      axisLabel: {
        formatter: '{value}'
      }
    }
  }
}
